import { useState, useEffect } from "react"
import "./User.css"
import AvatarSection from "../components/AvatarSection"
import {
  GetUserInfoService,
  fetchUserExpService,
  updatePasswordService,
  fetchCodesService,
  generateCodeService,
  fetchUploadedTorrentsService,
} from "../api/UserApi"
import { listUserPostsService, deletePostService } from "../api/CommunityApi"
import { useNavigate } from "react-router-dom"
import { Pagination } from 'antd'
import SeedDetail from "./SeedDetail"

const MAX_POINTS = [20, 100, 500, 2000, 5000, 8000, 12000, 999999]
const NEXT_NAMES = ["毕业生", "初级铁驭", "合格铁驭 ", "知名铁驭", "荣耀铁驭", "传奇铁驭", "BT 至尊", "MAX"]

function User() {
  const navigate = useNavigate()
  const [activeTab, setActiveTab] = useState("info")
  const [userInfo, setUserInfo] = useState(null)
  const [userExp, setUserExp] = useState(null)
  const [codes, setCodes] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)
  const [passwords, setPasswords] = useState({
    oldPassword: "",
    newPassword: "",
    confirmPassword: "",
  })
  const [errors, setErrors] = useState({
    current: "",
    new: "",
    confirm: "",
  })
  const [threads, setThreads] = useState([])
  const [deletingPostId, setDeletingPostId] = useState(null)
  const [showDeleteModal, setShowDeleteModal] = useState(false)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [successMessage, setSuccessMessage] = useState("")
  const [showModal, setShowModal] = useState(false)
  const [expireTime, setExpireTime] = useState(0)
  const [isGenerating, setIsGenerating] = useState(false)
  const [currentPage, setCurrentPage] = useState(1)
  const [pageSize, setPageSize] = useState(8)
  const [isDetailModalVisible, setIsDetailModalVisible] = useState(false);
  const [selectedSeedId, setSelectedSeedId] = useState(null);
  const [uploadedTorrents, setUploadedTorrents] = useState({
    rows: [],
    total: 0
  })
  const [seedsLoaded, setSeedsLoaded] = useState(false) // 新增状态标记

  useEffect(() => {
    const fetchData = async () => {
      console.log("Fetching user data...")
      try {
        setLoading(true)
        setError(null)

        const [infoRes, expRes, codeRes] = await Promise.all([
          GetUserInfoService(),
          fetchUserExpService(),
          fetchCodesService(),
        ])

        if (!infoRes.data || !expRes.data) {
          throw new Error("Invalid response data")
        }

        setUserInfo(infoRes.data)
        setUserExp(expRes.data)
        setCodes(codeRes.data)

        const response = await listUserPostsService(infoRes.data.id, 1, 200)
        if (response.success) {
          setThreads(response.data.postList || [])
        } else {
          console.error("获取帖子列表失败:", response.message)
        }
      } catch (err) {
        setError(err.message)
        console.error("Failed to load user data", err)
      } finally {
        setLoading(false)
      }
    }

    fetchData()
  }, [])

  useEffect(() => {
    if (activeTab === "seeds") {
      if (!seedsLoaded) {
        fetchUploadedTorrents(currentPage, pageSize)
        setSeedsLoaded(true)
      }
    }
  }, [activeTab, seedsLoaded, currentPage, pageSize])
// 添加种子详情关闭处理函数
const handleDetailModalClose = () => {
  setIsDetailModalVisible(false);
  setSelectedSeedId(null);
  };
  const handleSeedClick = (id) => {
    setSelectedSeedId(id);
    setIsDetailModalVisible(true);
  };
  const fetchUploadedTorrents = async (page = 1, size = 8) => {
    try {
      const response = await fetchUploadedTorrentsService(page, size)
      if (response.success && response.data) {
        setUploadedTorrents(response.data)
      } else {
        console.error("Failed to fetch uploaded torrents:", response.message)
        setUploadedTorrents({ rows: [], total: 0 })
      }
    } catch (error) {
      console.error("Error fetching uploaded torrents:", error)
      setUploadedTorrents({ rows: [], total: 0 })
    }
  }

  const handleChange = (e) => {
    const { name, value } = e.target
    setPasswords((prev) => ({
      ...prev,
      [name]: value,
    }))

    if (name === "confirmPassword") {
      validateConfirmPassword(value)
    }
  }

  const validateConfirmPassword = (confirm) => {
    if (confirm !== passwords.newPassword) {
      setErrors((prev) => ({
        ...prev,
        confirm: "两次输入的密码不一致",
      }))
      return false
    }
    setErrors((prev) => ({ ...prev, confirm: "" }))
    return true
  }

  const handleSubmit = async (e) => {
    e.preventDefault()
    setIsSubmitting(true)
    setSuccessMessage("")

    const isValid = [validateConfirmPassword(passwords.confirmPassword), !!passwords.currentPassword.trim()].every(
      (v) => v,
    )

    if (!isValid) {
      setIsSubmitting(false)
      return
    }

    try {
      const response = await updatePasswordService(userInfo.id, {
        password: passwords.oldPassword,
        newPassword: passwords.newPassword,
      })

      if (response.status === 200) {
        setSuccessMessage("密码修改成功！")
        setPasswords({
          oldPassword: "",
          newPassword: "",
          confirmPassword: "",
        })
      } else {
        setErrors((prev) => ({
          ...prev,
          current: response.message || "当前密码错误",
        }))
      }
    } catch (error) {
      console.error("修改密码失败:", error)
      setErrors((prev) => ({
        ...prev,
        current: error.response?.data?.message || "请求失败，请稍后重试",
      }))
    } finally {
      setIsSubmitting(false)
    }
  }

  const handleDeletePost = async () => {
    if (!deletingPostId) return
    try {
      await deletePostService(deletingPostId)
      setThreads((prev) => prev.filter((t) => t.id !== deletingPostId))
    } catch (err) {
      alert("删除失败，请稍后重试")
    } finally {
      setShowDeleteModal(false)
      setDeletingPostId(null)
    }
  }

  const calculateProgress = () => {
    if (!userInfo || !userExp) return 0

    const maxPoint = MAX_POINTS[userInfo.permissionGroup]
    return maxPoint ? (userExp.experience / maxPoint) * 100 : 0
  }

  const handleAvatarUpdate = (newAvatarUrl) => {
    setUserInfo(prev => ({
      ...prev,
      avatarUrl: newAvatarUrl
    }));
  };

  if (loading) {
    return (
      <div className="loading-container">
        <div className="loading-spinner"></div>
        <p>数据加载中...</p>
      </div>
    )
  }

  if (error) {
    return (
      <div className="error-container">
        <div className="error-icon">⚠️</div>
        <h3>加载失败</h3>
        <p>错误: {error}</p>
        <button className="retry-btn" onClick={() => window.location.reload()}>
          重试
        </button>
      </div>
    )
  }

  const handleModalClose = () => {
    setShowModal(false)
    setExpireTime(0)
  }

  const handleGenerateCode = async () => {
    if (!expireTime) return
    try {
      setIsGenerating(true)
      const response = await generateCodeService(expireTime)
      if (response.status === 200) {
        const updatedCodes = await fetchCodesService()
        setCodes(updatedCodes.data)
        handleModalClose()
      } else {
        handleModalClose()
        alert(response.msg || "生成邀请码失败")
      }
    } catch (error) {
      console.error("生成邀请码请求失败:", error)
    } finally {
      setIsGenerating(false)
    }
  }

  const handlePageChange = (page, size) => {
    setCurrentPage(page)
    setPageSize(size)
    fetchUploadedTorrents(page, size)
  }

  if (loading) {
    return (
      <div className="loading-container">
        <div className="loading-spinner"></div>
        <p>数据加载中...</p>
      </div>
    )
  }

  if (error) {
    return (
      <div className="error-container">
        <div className="error-icon">⚠️</div>
        <h3>加载失败</h3>
        <p>错误: {error}</p>
        <button className="retry-btn" onClick={() => window.location.reload()}>
          重试
        </button>
      </div>
    )
  }

  const renderContent = () => {
    switch (activeTab) {
      case "info":
        return (
          <div className="content-card">
            <div className="card-header">
              <h2>👤 用户信息</h2>
            </div>
            <div className="card-body">
              <div className="info-grid">
                <div className="info-item">
                  <div className="info-label">用户名</div>
                  <div className="info-value">{userInfo.username}</div>
                </div>
                <div className="info-item">
                  <div className="info-label">邮箱</div>
                  <div className="info-value">{userInfo.email}</div>
                </div>
                <div className="info-item">
                  <div className="info-label">上传量</div>
                  <div className="info-value highlight">{userExp.uploaded}</div>
                </div>
                <div className="info-item">
                  <div className="info-label">下载量</div>
                  <div className="info-value highlight">{userExp.downloaded}</div>
                </div>
                <div className="info-item">
                  <div className="info-label">BT币</div>
                  <div className="info-value coin">{userExp.bt}</div>
                </div>
                <div className="info-item">
                  <div className="info-label">分享率</div>
                  <div className="info-value coin">{userExp.ratio}</div>
                </div>
              </div>

              <div className="avatar-section">
                <h3>头像设置</h3>
                <AvatarSection 
                  url={userInfo.avatarUrl} 
                  userId={userInfo.id}
                  onAvatarUpdate={handleAvatarUpdate}
                />
              </div>
            </div>
          </div>
        )

      case "password":
        return (
          <div className="content-card">
            <div className="card-header">
              <h2>🔒 修改密码</h2>
            </div>
            <div className="card-body">
              <form onSubmit={handleSubmit} className="password-form">
                <div className="form-group">
                  <label>当前密码</label>
                  <input
                    type="password"
                    name="oldPassword"
                    placeholder="请输入当前密码"
                    value={passwords.oldPassword}
                    onChange={handleChange}
                    className={`form-input ${errors.current ? "error" : ""}`}
                    disabled={isSubmitting}
                  />
                  {errors.current && <div className="error-message">{errors.current}</div>}
                </div>

                <div className="form-group">
                  <label>新密码</label>
                  <input
                    type="password"
                    name="newPassword"
                    placeholder="请输入新密码"
                    value={passwords.newPassword}
                    onChange={handleChange}
                    className={`form-input ${errors.new ? "error" : ""}`}
                    disabled={isSubmitting}
                  />
                  {errors.new && <div className="error-message">{errors.new}</div>}
                </div>

                <div className="form-group">
                  <label>确认新密码</label>
                  <input
                    type="password"
                    name="confirmPassword"
                    placeholder="请再次输入新密码"
                    value={passwords.confirmPassword}
                    onChange={handleChange}
                    className={`form-input ${errors.confirm ? "error" : ""}`}
                    disabled={isSubmitting}
                  />
                  {errors.confirm && <div className="error-message">{errors.confirm}</div>}
                </div>

                <button
                  type="submit"
                  className={`btn btn-primary ${isSubmitting ? "loading" : ""}`}
                  disabled={isSubmitting}
                >
                  {isSubmitting ? (
                    <>
                      <span className="btn-spinner"></span>
                      正在提交...
                    </>
                  ) : (
                    "确认修改"
                  )}
                </button>

                {successMessage && (
                  <div className="success-message">
                    <span className="success-icon">✅</span>
                    {successMessage}
                  </div>
                )}
              </form>
            </div>
          </div>
        )

      case "level":
        return (
          <div className="content-card">
            <div className="card-header">
              <h2>⭐ 用户等级</h2>
            </div>
            <div className="card-body">
              <div className="level-info">
                <div className="current-level">
                  <div className="level-badge">{userInfo.permissionGroupName}</div>
                  <div className="level-details">
                    <p className="exp-text">
                      经验值: <span className="exp-current">{userExp.experience}</span> /
                      <span className="exp-max">{MAX_POINTS[userInfo.permissionGroup]}</span>
                    </p>
                  </div>
                </div>

                <div className="progress-container">
                  <div className="progress-bar">
                    <div className="progress-fill" style={{ width: `${calculateProgress()}%` }}>
                      <div className="progress-shine"></div>
                    </div>
                  </div>
                  <div className="progress-text">{calculateProgress().toFixed(1)}%</div>
                </div>

                <div className="next-level">
                  <span className="next-level-text">
                    下一等级: <strong>{NEXT_NAMES[userInfo.permissionGroup]}</strong>
                  </span>
                </div>
              </div>
            </div>
          </div>
        )

        case "seeds":
          return (
            <div className="content-card">
              <div className="card-header">
                <h2>🌱 种子列表</h2>
              </div>
              <div className="card-body">
                {!uploadedTorrents || !uploadedTorrents.rows || uploadedTorrents.rows.length === 0 ? (
                  <div className="empty-state">
                    <div className="empty-icon">📦</div>
                    <p>暂无种子数据</p>
                  </div>
                ) : (
                  <>
                    <div className="list-container">
                      {uploadedTorrents.rows.map((torrent) => (
                        <div key={torrent.id} className="list-item">
                          <div className="item-header">
                            <div className="item-title">{torrent.title}</div>
                            <div className={`item-status ${torrent.underReview ? 'review' : 'published'}`}>
                              {torrent.underReview==0 ? '审核中' : '已发布'}
                            </div>
                          </div>
                          <div className="item-meta" onClick={() => handleSeedClick(torrent.id)}>
                            <span className="meta-item">大小: {(torrent.size / 1024 / 1024).toFixed(2)} MB</span>
                            <span className="meta-item">标签: {torrent.tags}</span>
                            <span className="meta-item">创建时间: {torrent.createTime.replace('T', ' ')}</span>
                          </div>
                          <div className="item-description">
                            {torrent.description || '暂无描述'}
                          </div>
                        </div>
                      ))}
                    </div>
                    <Pagination
                      current={currentPage}
                      pageSize={pageSize}
                      total={uploadedTorrents.total || 0}
                      onChange={handlePageChange}
                      showSizeChanger
                      showQuickJumper
                    />
                  </>
                )}
              </div>
            </div>
            
          )

      case "posts":
        return (
          <div className="content-card">
            <div className="card-header">
              <h2>📝 帖子列表</h2>
            </div>
            <div className="card-body">
              {threads.length === 0 ? (
                <div className="empty-state">
                  <div className="empty-icon">📄</div>
                  <p>暂无帖子数据</p>
                </div>
              ) : (
                <div className="list-container">
                  {threads.map((thread, id) => (
                  <div key={id} className="list-item" style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                    <div>
                      <div className="item-category">{thread.category}</div>
                     <div
                      className="item-title"
                      style={{ cursor: "pointer", color: "#1890ff" }}
                      onClick={() => navigate(`/community/${thread.id}`)}
                    >
                      {thread.title}
                    </div>
                      <div className="item-meta">
                        点赞: {thread.likeCount} | 回复: {thread.commentCount} | 浏览: {thread.viewCount}
                      </div>
                    </div>
                    <button
                      className="btn btn-outline"
                      style={{ marginLeft: 24, minWidth: 80, color: "#ff6699", borderColor: "#ff6699" }}
                      onClick={() => {
                        setDeletingPostId(thread.id)
                        setShowDeleteModal(true)
                      }}
                    >
                      删除
                    </button>
                  </div>
                ))}
                </div>
              )}
              {showDeleteModal && (
                <div className="modal-overlay" onClick={() => setShowDeleteModal(false)}>
                  <div className="modal-content" onClick={e => e.stopPropagation()}>
                    <div className="modal-header">
                      <h3>确认删除</h3>
                      <button className="modal-close" onClick={() => setShowDeleteModal(false)}>×</button>
                    </div>
                    <div className="modal-body">
                      <p>确定要删除该帖子吗？删除后不可恢复。</p>
                    </div>
                    <div className="modal-footer">
                      <button className="btn btn-outline" onClick={() => setShowDeleteModal(false)}>
                        取消
                      </button>
                      <button
                        className="btn btn-primary"
                        style={{ background: "#ff6699", border: "none" }}
                        onClick={handleDeletePost}
                      >
                        确认删除
                      </button>
                    </div>
                  </div>
                </div>
              )}
            </div>
          </div>
        )

      case "codes":
        return (
          <div className="content-card">
            <div className="card-header">
              <h2>🎫 邀请码</h2>
              <button className="btn btn-primary" onClick={() => setShowModal(true)}>
                生成邀请码
              </button>
            </div>
            <div className="card-body">
              {codes.length === 0 ? (
                <div className="empty-state">
                  <div className="empty-icon">🎫</div>
                  <p>暂无邀请码</p>
                  <button className="btn btn-outline" onClick={() => setShowModal(true)}>
                    立即生成
                  </button>
                </div>
              ) : (
                <div className="table-container">
                  <table className="data-table">
                    <thead>
                      <tr>
                        <th>邀请码</th>
                        <th>创建时间</th>
                        <th>状态</th>
                        <th>是否使用</th>
                        <th>有效期</th>
                      </tr>
                    </thead>
                    <tbody>
                      {codes.map((code, id) => (
                        <tr key={id} className={code.isExpired ? "expired" : ""}>
                          <td>
                            <code className="code-text">{code.code}</code>
                          </td>
                          <td>{code.createTime?.replace("T", " ")}</td>
                          <td>
                            <span className={`status-badge ${code.isExpired ? "expired" : "active"}`}>
                              {code.isExpired ? "已过期" : "有效"}
                            </span>
                          </td>
                          <td>{code.isUsed? "已使用": "未使用"}</td>
                          <td>{code.expiresTime?.replace("T", " ")}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}

              {showModal && (
                <div className="modal-overlay" onClick={handleModalClose}>
                  <div className="modal-content" onClick={(e) => e.stopPropagation()}>
                    <div className="modal-header">
                      <h3>设置邀请码有效期</h3>
                      <button className="modal-close" onClick={handleModalClose}>
                        ×
                      </button>
                    </div>
                    <div className="modal-body">
                      <div className="radio-group">
                        {[24, 48, 72].map((value) => (
                          <label key={value} className="radio-item">
                            <input
                              type="radio"
                              name="expire"
                              value={value}
                              checked={expireTime === value}
                              onChange={() => setExpireTime(value)}
                            />
                            <span className="radio-label">{value} 小时</span>
                          </label>
                        ))}
                      </div>
                    </div>
                    <div className="modal-footer">
                      <button className="btn btn-outline" onClick={handleModalClose}>
                        取消
                      </button>
                      <button
                        className={`btn btn-primary ${isGenerating ? "loading" : ""}`}
                        onClick={handleGenerateCode}
                        disabled={isGenerating || !expireTime}
                      >
                        {isGenerating ? (
                          <>
                            <span className="btn-spinner"></span>
                            生成中...
                          </>
                        ) : (
                          "确认生成"
                        )}
                      </button>
                    </div>
                  </div>
                </div>
              )}
            </div>
          </div>
        )

      default:
        return null
    }
  }

  return (
    <div className="user-page">
      <div className="sidebar">
        <div className="sidebar-header">
          <div className="user-avatar">
            <img src={userInfo?.avatarUrl || "/placeholder.svg?height=50&width=50"} alt="Avatar" />
          </div>
          <h3 className="username">{userInfo?.username}</h3>
          <div className="user-level">{userInfo?.permissionGroupName}</div>
        </div>

        <nav className="sidebar-nav">
          <ul>
            <li onClick={() => setActiveTab("info")} className={activeTab === "info" ? "active" : ""}>
              <span className="nav-icon">👤</span>
              用户信息
            </li>
            <li onClick={() => setActiveTab("password")} className={activeTab === "password" ? "active" : ""}>
              <span className="nav-icon">🔒</span>
              修改密码
            </li>
            <li onClick={() => setActiveTab("level")} className={activeTab === "level" ? "active" : ""}>
              <span className="nav-icon">⭐</span>
              用户等级
            </li>
            <li onClick={() => setActiveTab("seeds")} className={activeTab === "seeds" ? "active" : ""}>
              <span className="nav-icon">🌱</span>
              种子列表
            </li>
            <li onClick={() => setActiveTab("posts")} className={activeTab === "posts" ? "active" : ""}>
              <span className="nav-icon">📝</span>
              帖子列表
            </li>
            <li onClick={() => setActiveTab("codes")} className={activeTab === "codes" ? "active" : ""}>
              <span className="nav-icon">🎫</span>
              邀请码
            </li>
          </ul>
        </nav>
      </div>

      <div className="main-content">
        <div className="content-wrapper">{renderContent()}</div>
      </div>

      {selectedSeedId && (
              <SeedDetail
                id={selectedSeedId}
                visible={isDetailModalVisible}
                onClose={handleDetailModalClose}
              />
            )}
    </div>
  )
}

export default User